<template>
  <div class="child-page">
    <!-- 在此处新加按钮-->
    <button @click="handleClick">[data]发送数据</button>
    <button @click="handleFullClick">[globalData]发送全局数据</button>
    <div id="child-app-container">
      <micro-app
        v-if="canMount"
        name="child-app"
        url="http://localhost:3001/"
        baseroute="/child-app"
        :data="data"
        @created="handleCreated"
        @beforemount="handleBeforeMount"
        @mounted="handleMounted"
        @unmount="handleUnmount"
        @error="handleError"
        inline
        keep-route-state
        disableSandbox="true"
      ></micro-app>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, onUnmounted } from 'vue'
import microApp,{EventCenterForMicroApp} from '@micro-zoe/micro-app'
let microAppInstance: any = null
let isMounted = ref(false)
const canMount = ref(false)
const appName = ref('child-app');
const data = ref({
  appName: appName.value,
  from: 'base-app',
});

interface MicroAppEvent extends CustomEvent {
  detail: {
    microApp: any
    container: any
    name: string
  }
}

// 修改事件中心的创建方式
window.eventCenterForChildApp = new EventCenterForMicroApp(appName.value);

// 接收指定子应用的消息
window.eventCenterForChildApp.addDataListener((data: any) => {
  console.log('【主应用】收到子应用消息:', data);
});

//发送数据
const handleClick = () => {
  console.log('【主应用】准备发送数据到子应用:', appName.value);
  window.eventCenterForChildApp.dispatch({
    type: 'main-msg',
    data: {
      msg: '来自主应用的消息',
      timestamp: Date.now()
    }
  });
}

//发送全局数据
const handleFullClick = () => {
  console.log('【主应用】准备发送全局数据');
  const globalData = {
    type: 'global-msg',
    from: 'main',
    data: {
      msg: '来自主应用的全局消息',
      timestamp: Date.now()
    }
  };
  microApp.setGlobalData(globalData);
}

const handleCreated = (e: MicroAppEvent) => {
  console.log('micro-app-blog created--', e.detail)
  if (!e.detail) {
    console.log('event.detail 为空')
    return
  }
  
  // 等待子应用注册完成
  const checkInstance = () => {
    // @ts-ignore
    microAppInstance = window['micro-app-child-app']
    console.log('检查 microAppInstance:', microAppInstance)

    if (!microAppInstance) {
      console.log('等待子应用注册...')
      window.__MICRO_APP_ENVIRONMENT__ = true
      window.__MICRO_APP_PUBLIC_PATH__ = `${window.location.origin}/child/`
      window.__MICRO_APP_BASE_ROUTE__ = '/child'
      window.__MICRO_APP_NAME__ = 'child-app'
      setTimeout(checkInstance, 100)
      return
    }

    // 等待 micro-app-body 元素准备就绪
    const waitForContainer = () => {
      const container = document.querySelector('micro-app-body')
      if (!container) {
        console.log('等待挂载点准备...')
        setTimeout(waitForContainer, 50)
        return
      }

      console.log('准备挂载子应用, microAppInstance:', microAppInstance)
      try {
        if (typeof microAppInstance.mount === 'function') {
          console.log('开始执行 mount 方法')
          microAppInstance.mount()
          isMounted.value = true
          console.log('子应用手动挂载成功')
        } else {
          console.error('mount 方法不存在,microAppInstance:', microAppInstance)
        }
      } catch (e) {
        console.error('子应用挂载失败:', e)
        isMounted.value = false
      }
    }

    waitForContainer()
  }

  checkInstance()
}

const handleBeforeMount = () => {
  console.log('micro-app-blog beforemount')
}

const handleMounted = () => {
  console.log('micro-app-blog mounted')
  // 移除这里的 mount 调用，避免重复挂载
  isMounted.value = true
}

const handleUnmount = () => {
  console.log('micro-app-blog unmount')
  if (isMounted.value && microAppInstance) {
    try {
      microAppInstance.unmount()
      microAppInstance = null
      isMounted.value = false
    } catch (e) {
      console.error('Unmount error:', e)
    }
  }
}

const handleError = (e: MicroAppEvent) => {
  console.error('micro-app-blog error:', e.detail)
}

onMounted(() => {
  console.log('Child component mounted')
  canMount.value = true
})

onBeforeUnmount(() => {
  console.log('Child component onBeforeUnmount')
  canMount.value = false
  if (isMounted.value && microAppInstance) {
    try {
      microAppInstance.unmount()
      microAppInstance = null
      isMounted.value = false
    } catch (e) {
      console.error('Unmount error:', e)
    }
  }
})

onUnmounted(() => {
  console.log('Child component unmounted')
  microApp.clearGlobalDataListener()
})
</script>

<style scoped>
.child-page {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

#child-app-container {
  flex: 1;
  width: 100%;
  position: relative;
}

:deep(micro-app) {
  width: 100%;
  height: 100%;
}
</style>